package com.css.bjdt_core.explain.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.explain.entity.RptExplainExportExcel;
import com.css.bjdt_core.util.CommonUtil;

@Service
public class ReportExplainExportExcelService {

	@Autowired
	private Dao dao;

	@Autowired
	private ReportTemplateExplainService reportTemplateExplainService;

	public List<RptExplainExportExcel> rptExplainExportExcel(String dzzId, String annualId, String explainId,
			String querySql, final String columnNum) {

		//先获得SQL
		/*RptTemplateExplain rptTemplateExplain = reportTemplateExplainService.getARptTemplateExplain(explainId);
		String querySql = rptTemplateExplain.getExportExcelSql();
		final String columnNum = rptTemplateExplain.getExportExcelLength();*/

		Sql sql = Sqls.create(querySql);
		sql.params().set("dzzId", dzzId);

		//根据SQL先查出来该张报表的所有审核信息
		sql.setCallback(new SqlCallback() {

			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				List<RptExplainExportExcel> rptExplainExportExcelList = new ArrayList<RptExplainExportExcel>();
				while (rs.next()) {
					RptExplainExportExcel rptExplainExportExcel = new RptExplainExportExcel();
					rptExplainExportExcel.setDzzJc(rs.getString("DZZJC"));
					for (int a = 1; a <= Integer.parseInt(columnNum); a++) {
						String columnStr = "第" + CommonUtil.toChinese(a + "") + "列";
						String columnValue = rs.getString(columnStr);
						//利用反射，赋值
						StringBuffer sb = new StringBuffer();
						sb.append("set");
						sb.append("column".substring(0, 1).toUpperCase());
						sb.append("column".substring(1, 6)).append(a + "");
						try {
							Method setMethod = rptExplainExportExcel.getClass().getMethod(sb.toString(), String.class);
							setMethod.invoke(rptExplainExportExcel, new Object[] { columnValue });
						} catch (NoSuchMethodException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					rptExplainExportExcelList.add(rptExplainExportExcel);
				}
				return rptExplainExportExcelList;
			}
		});
		dao.execute(sql);
		return sql.getList(RptExplainExportExcel.class);
	}
}
